<template>
  <div class="data-management">
    <el-card class="data-upload">
      <template #header>
        <div class="card-header">
          <span>数据上传</span>
        </div>
      </template>
      
      <el-upload
        class="upload-area"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .csv, .xlsx 格式的数据文件
          </div>
        </template>
      </el-upload>

      <div class="upload-actions">
        <el-button type="primary" @click="handleUpload" :loading="uploading">
          开始上传
        </el-button>
        <el-button @click="handleClear">清空</el-button>
      </div>
    </el-card>

    <el-card class="data-list">
      <template #header>
        <div class="card-header">
          <span>数据列表</span>
          <el-input
            v-model="search"
            placeholder="搜索数据集"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table
        :data="filteredTableData"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="数据集名称" />
        <el-table-column prop="type" label="数据类型" />
        <el-table-column prop="size" label="数据量" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已处理' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button-group>
              <el-button size="small" @click="handleView(scope.row)">
                查看
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 数据预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="数据预览"
      width="80%"
    >
      <el-table :data="previewData" height="400">
        <el-table-column 
          v-for="col in previewColumns" 
          :key="col"
          :prop="col"
          :label="col"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { UploadFilled, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { datasetApi, fileApi } from '@/api'

// 上传相关
const uploading = ref(false)
const fileList = ref([])

const handleFileChange = (file) => {
  fileList.value.push(file.raw)
}

const handleUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }

  uploading.value = true
  try {
    const response = await datasetApi.uploadDataset(fileList.value)
    console.log(response);
    
    ElMessage.success('上传成功')
    // 刷新文件列表
    fetchFileList()
  } catch (error) {
    ElMessage.error(`上传失败66: ${error.response?.data?.detail || error.message}`)
  } finally {
    uploading.value = false
    fileList.value = []
  }
}

const handleClear = () => {
  fileList.value = []
}

// 表格数据
const loading = ref(false)
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 获取文件列表
const fetchFileList = async () => {
  loading.value = true
  try {
    const response = await fileApi.getFileList()
    if (response.files) {
      tableData.value = response.files.map(filename => ({
        name: filename,
        // type: filename.includes('load') ? '负荷数据' : 
        //       filename.includes('wind') ? '风电数据' : 
        //       filename.includes('solar') ? '光伏数据' : '其他',
        type: "测试",
        size: '计算中...',
        updateTime: new Date().toLocaleDateString(),
        status: filename.includes('processed') ? '已处理' : '处理中'
      }))
      total.value = tableData.value.length
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const filteredTableData = computed(() => {
  return tableData.value.filter(data => {
    return data.name.toLowerCase().includes(search.value.toLowerCase())
  })
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 数据预览
const previewVisible = ref(false)
const previewData = ref([])
const previewColumns = ref([])

const handleView = async (row) => {
  previewVisible.value = true
  try {
    // 模拟数据预览
    previewColumns.value = ['时间', '数值', '天气', '温度']
    previewData.value = [
      { '时间': '2024-03-20 00:00', '数值': 100, '天气': '晴', '温度': 25 },
      { '时间': '2024-03-20 01:00', '数值': 110, '天气': '晴', '温度': 24 }
    ]
  } catch (error) {
    ElMessage.error('获取数据预览失败')
  }
}

// 删除处理
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除数据集 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await fileApi.deleteFile(row.name)
      ElMessage.success('删除成功')
      fetchFileList() // 刷新列表
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  })
}

// 初始加载
onMounted(() => {
  fetchFileList()
})
</script>

<style scoped>
.data-management {
  padding: 20px;
}

.data-upload {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-area {
  width: 100%;
}

.upload-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}
</style> 